import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权
import { getMenuList } from '@/api/login'
import { asynRouterMap, constantRouterMap } from '@/router'
import resRouter from './resRouter'
//import de from 'element-ui/src/locale/lang/de' //动态路由


const whiteList = ['/login'] // 不重定向白名单


router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if pageNum page is dashboard will not trigger	afterEach hook, so manually handle it
    }else{
      next()
    }
    // else {
    //   if (!store.getters.shopMenuList.length) {
    //     getMenuList().then(res => {
    //       if(res.body) {
    //         //routerGo(resRouter, to, next)
    //         routerGo(res.body, to, next)
    //       }
    //     })
    //   }else{
    //     next()
    //   }
    // }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

/**
 *
 * @param userMenu api获取的角色菜单
 * @returns {Array}
 */
function getAsyncRouter (userMenu) {
  let parseList =  setGridDataFromTree([], userMenu) || []
  let dynamicRouter = parseList.filter(item =>/isDynamic/.test(item.url)) || []//获取所有动态路由配置
  console.log(dynamicRouter);
  let filterRouter = filterAsyncRouter(dynamicRouter)  //动态添加板块
  let restultMenu = filterTree(filterRouter,restultmap(parseList))
  return restultMenu
}

/**
 * 过滤api获取的菜单的key
 * @param list
 * @returns {Array}
 */
function restultmap(list) {
  let names = []
  if(list && list.length > 0) {
    list.forEach(element => {
      names.push(element.url)
    });
  }else {
    Message.warning("暂无任何权限，请联系管理员！")
  }
  return names
}

function setGridDataFromTree(list, dataSource) {
  if (!(Array.isArray(dataSource) && dataSource.length > 0))
    return;
  dataSource.forEach((father) => {
    list.push(father);
    if (typeof (father.children) == "undefined") {} else {
      setGridDataFromTree(list, father.children);
    }
  });
  return list
}

/**
 * 对比本地与角色菜单配置，生成角色菜单
 * @param tree
 * @param map
 * @param arr
 * @returns {Array}
 */
function filterTree(tree = [], map = [], arr = []) {
  if (!tree.length) return []
  for (let item of tree) {
    if (!map.includes(item.key)) continue
    let node = {
      ...item,
      children: []
    }
    arr.push(node)
    if (item.children && item.children.length) filterTree(item.children, map, node.children)
  }
  return arr
}

/*function filterAsyncRouter(parseList) {
  let musicRouter = parseList.filter(item=>item.parentId==='16')
  let mallPlateRouter = parseList.filter(item=>item.parentId==='154')
  let weappPlateRouter = parseList.filter(item=>item.parentId==='155')
  asynRouterMap.forEach(element => {
    if (element.name === "course") {
      element.children.forEach(child => {
        if (child.name === "musicManage") {
          musicRouter.forEach(item => {
            child.children.push({
              name: item.url,
              key: item.url,
              path: item.url,
              component: () => import('@/views/course/musicManage/musicList/list'),
              meta: {
                title: item.name
              },
            })
          })
        }
      })
    }
    if (element.name === "operation") {
      element.children.forEach(child => {
        if (child.name === "mallPlateManage") {
          mallPlateRouter.forEach(item => {
            child.children.push({
              name: item.url,
              key: item.url,
              path: item.url,
              component: () => import('@/views/system/plateManage/mallPlate/plateGoodsList'),
              meta: {
                title: item.name
              },
            })
          })
        }
        if (child.name === "weappPlateManage") {
          weappPlateRouter.forEach(item => {
            child.children.push({
              name: item.url,
              key: item.url,
              path: item.url,
              component: () => import('@/views/system/plateManage/mallPlate/plateGoodsList'),
              meta: {
                title: item.name
              },
            })
          })
        }
      })
    }

  })
  return asynRouterMap
}*/
function routerGo(userMenu, to, next) {
  let getRouter = getAsyncRouter(userMenu)   // //过滤路由
  let routes = constantRouterMap.concat(getRouter)
  router.options.routes = routes
  store.dispatch('getShopMenuList', routes);
  router.addRoutes(getRouter) //动态添加路由
  next({ ...to, replace: true })
}

router.afterEach(() => {
  NProgress.done() // 结束Progress
})


